package com.hbun.cxcy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hbun.cxcy.common.utils.PageUtils;
import com.hbun.cxcy.common.utils.Query;
import com.hbun.cxcy.entity.Achievement;
import com.hbun.cxcy.entity.User;
import com.hbun.cxcy.mapper.UserMapper;
import com.hbun.cxcy.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbun.cxcy.utils.JWTUtils;
import com.hbun.cxcy.vo.LoginVo;
import com.hbun.cxcy.vo.RegisterVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.hutool.crypto.SecureUtil;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mahaunyu
 * @since 2022-01-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<User> page = this.page(new Query<User>().getPage(params),
                new QueryWrapper<>());
        return new PageUtils(page);
    }

    /**
     * 邮箱注册功能
     *
     * @param register
     * @return
     */
    @Async
    @Override
    public int register(RegisterVo register) {
        // 检验验证码
        String code = register.getCode();
        String redisCode = redisTemplate.opsForValue().get("email:code" + register.getEmail());
        if (!StringUtils.isEmpty(redisCode)) {
            // 说明存在验证码，并且没有失效
            if (code.equals(redisCode.split("_")[0])) {
                // 说明相等，瞬间删除缓存
                redisTemplate.delete("email:code" + register.getEmail());
                // 注册
                User user = new User();
                BeanUtils.copyProperties(register, user);
                user.setCreateTime(new Date());
                user.setUpdateTime(new Date());
                user.setStatus(1);
                // MD5盐值加密--这个类需要导入安全模块
//                BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//                String encode = passwordEncoder.encode(register.getPassword());
                String encode = SecureUtil.md5(register.getPassword());
                user.setPassword(encode);
                return this.baseMapper.insert(user);
            } else {
                // 说明验证码不正确
                return 0;
            }
        } else {
            // 验证码不存在或者失效
            return 0;
        }


    }

    @Override
    public String login(LoginVo loginVo) {
        String email = loginVo.getEmail();

        QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("email", email);
        wrapper.and(w->{
            w.eq("status",1);
        });
        User user = this.baseMapper.selectOne(wrapper);
        if (user == null) {
            return null;
        }
        // 说明邮箱存在，下面判断密码
        String password = loginVo.getPassword();
        String pwd = user.getPassword();
//        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//        boolean matches = passwordEncoder.matches(password, pwd);
        boolean matches = pwd.equals(SecureUtil.md5(password));
        if (matches) {
            // 匹配成功，生成token
            return JWTUtils.geneJsonWebToken(user);
        } else {
            return null;
        }

    }

    @Override
    public void removeByIdsWithCustom(List<Long> ids) {
        for (Long id : ids) {
            User user = this.baseMapper.selectById(id);
            user.setStatus(0);
            this.updateById(user);
        }
    }

    @Override
    public void updateByIdWithCustom(User user) {
        user.setUpdateTime(new Date());
        this.updateById(user);
    }
}
